package com.ft.scan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ft.scan.common.PasswordEncryptionUtils;
import com.ft.scan.common.WxResult;
import com.ft.scan.config.WxConfig;
import com.ft.scan.domain.User;
import com.ft.scan.mapper.UserMapper;
import com.ft.scan.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.List;

/**
 * 用户Service业务层处理
 *
 * @author wujie
 * {@code @date} 2024-01-26
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WxConfig wxConfig;
    @Autowired
    private PasswordEncryptionUtils passwordEncryptionUtils;

    /**
     * 查询用户列表
     *
     * @param username 用户名
     * @param password 密码
     * @return 用户
     */
    @Override
    public User selectUserByUsernameAndPassword(String username, String password) {
        List<User> users = userMapper.selectUserByUsername(username);
        if (!users.isEmpty()) {
            for (User user : users) {
                String pwd = user.getPassword();
                if (!pwd.isEmpty() && pwd.equals(password)) {
                    return user;
                }
            }
        }
        return null;
    }

    /**
     * 微信登录查询用户
     *
     * @param openid 微信登录openid
     * @return 用户
     */
    @Override
    public User selectUserByOpenid(String openid) {
        return userMapper.selectUserByOpenid(openid);
    }

    /**
     * 根据手机号查询用户
     * @param mobile 手机号
     * @return User 用户对象，如果不存在则返回null
     */
    @Override
    public User selectUserByMobile(String mobile){
        return userMapper.selectUserByMobile(mobile);
    }

    /**
     * 根据ID查询用户
     *
     * @param userid 用户ID
     * @return 用户
     */
    @Override
    public User selectUserByUserId(Long userid) {
        return userMapper.selectUserByUserId(userid);
    }

    /**
     * 查询用户列表
     *
     * @param user 用户
     * @return 用户
     */
    @Override
    public List<User> selectUserList(User user) {
        return userMapper.selectUserList(user);
    }


    /**
     * 修改用户
     *
     * @param user 用户
     * @return 结果
     */
    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    /**
     * 批量删除用户
     *
     * @param userIds 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteUserByUserIds(Long[] userIds) {
        return userMapper.deleteUserByUserIds(userIds);
    }

    /**
     * 删除用户信息
     *
     * @param userId 用户主键
     * @return 结果
     */
    @Override
    public int deleteUserByUserId(Long userId) {
        return userMapper.deleteUserByUserId(userId);
    }

    /**
     * 根据用户名和密码注册用户
     */
    @Override
    public int insertUserByUsernameAndPassword(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setToken(100);
        return userMapper.insertUser(user);
    }

    /**
     * 根据 OpenID 注册用户
     */
    @Override
    public int insertUserByOpenID(String openid, String nickName, String avatarUrl) {
        User user = new User();
        user.setUsername("New User");
        user.setPassword("123456");
        user.setAvatar(avatarUrl);
        user.setOpenid(openid);
        user.setNickname(nickName);
        user.setToken(100);
        return userMapper.insertUser(user);
    }

    /**
     * 根据 手机号注册用户
     */
    @Override
    public int insertUserByMobile(String mobile) {
        User user = new User();
        user.setUsername(mobile);
        user.setPassword("123456");
        user.setMobile(mobile);
        user.setToken(100);
        return userMapper.insertUser(user);
    }


    @Override
    public List<User> selectUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }



    @Override
    public WxResult getOpenIdByCode(String code) {
        String appId = wxConfig.getAppId();
        String appSecret = wxConfig.getAppSecret();
        String url = "https://api.weixin.qq.com/sns/jscode2session" + "?appId=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        String rst = null;

        try {
            rst = sendGetRequest(url);
        } catch (Exception e) {
            System.out.println("获取OpenId 发送GET 请求错误 ====>  {}" + e.getMessage());
            e.printStackTrace();
            return null;
        }

        if (rst != null && rst.isEmpty()) {
            return null;
        }

        JSONObject jsonObject = JSONObject.parseObject(rst);

        if (jsonObject != null) {

            return (jsonObject.getString("errcode") == null) ? WxResult.success(jsonObject.getString("openid"), jsonObject.getString("session_key"), jsonObject.getString("unionid")):
                        WxResult.fail(Integer.parseInt(jsonObject.getString("errcode")), jsonObject.getString("errmsg"));
        }
        return null;
    }


    @Override
    public String sendGetRequest(String url) {
        try {
            URI uri = new URI(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) uri.toURL().openConnection();
            httpURLConnection.setRequestProperty("Content-Type", "text/html");
            httpURLConnection.setRequestMethod("GET");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "GBK"));

            StringBuilder stringBuilder = new StringBuilder();

            String temp = null;

            if ((temp = bufferedReader.readLine()) != null) {
                stringBuilder.append(temp);
                stringBuilder.append("\n");
            }

            bufferedReader.close();
            return stringBuilder.toString();
        }catch (Exception e) {
            System.out.println("获取OpenId 发送GET 请求错误 ====>  {}" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

}
